<template>
  <!-- 订单支付页面  -->
  <div>
    <el-row :gutter="20">
      <!--左侧布局-->
      <el-col :span="6">
        <!-- 商品录入 -->
        <el-card>
          <div slot="header"><span>商品录入</span></div>
          <el-form label-width="80px" :model="enterItemForm" ref="enterItemForm" :rules="rules">
            <el-form-item label="商品编码" prop="itemSn">
              <el-input placeholder="请输入条码" v-model="enterItemForm.itemSn" clearable
                        @keyup.enter.native="enterItem"></el-input>
            </el-form-item>
            <el-form-item label="订购数量" prop="quantity">
              <el-input  placeholder="请输入数量" v-model.number="enterItemForm.quantity" clearable
                        @keyup.enter.native="enterItem"></el-input>
            </el-form-item>
            <el-button type="primary" @click="enterItem" :disabled="step!==2">ENTER ITEM</el-button>
            <el-button type="warning" @click="endSale" :disabled="step!==2 || saleItemList.length===0">END SALE
            </el-button>
          </el-form>
        </el-card>
        <!-- 订单支付 -->
        <el-card>
          <div slot="header"><span>订单支付</span></div>
          <el-form label-width="80px" :model="makePaymentForm">
            <el-form-item label="付款金额" prop="cashTendered">
              <el-input v-model="makePaymentForm.cashTendered"></el-input>
            </el-form-item>
            <el-form-item label="找零" prop="changeDue">
              <el-input v-model="changeDue"></el-input>
            </el-form-item>
            <el-button type="danger" :disabled="step !== 4" @click="makePayment">MAKE PAYMENT</el-button>
          </el-form>
        </el-card>
      </el-col>
      <!--右侧布局-->
      <el-col :span="18">
        <!--会员信息+订单信息-->
        <el-descriptions class="el-description" :column="3" :size="size" border>
          <template slot="extra">
            <el-button type="success" :disabled="step!==1" round @click="makeNewSale">MAKE NEW SALE</el-button>
          </template>
          <!-- 会员 -->
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-user"></i> 会员
            </template>
            张三
          </el-descriptions-item>

          <!--订单号 -->
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-mobile-phone"></i> 订单号
            </template>
            {{ orderInfo.saleNo }}
          </el-descriptions-item>

          <!--总金额 -->
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-location-outline"></i> 总金额
            </template>
            {{ orderInfo.total }}
          </el-descriptions-item>

          <!--总件数 -->
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-tickets"></i> 总件数
            </template>
            {{ orderInfo.quantity }}
          </el-descriptions-item>

          <!-- 状态 -->
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i> 状态
            </template>
            <el-tag size="small">{{ orderInfo.status }}</el-tag>
          </el-descriptions-item>

          <!--备注 -->
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-office-building"></i> 备注
            </template>
            暂无
          </el-descriptions-item>
        </el-descriptions>
        <!--订单明细 -->
        <el-card>
          <div slot="header"><span>订单明细</span></div>
          <el-table :data="saleItemList"
                    :row-class-name="rowSaleItemIndex"
                    max-height="250"
                    :header-cell-style="{textAlign:'center'}"
                    :cell-style="{textAlign:'center'}">
            <template slot="empty">
              <i class="el-icon-shopping-cart-2" style="font-size: 128px;display: inline-block;margin-top: 20px"></i>
              <p class="order_text">你的购物车空空如也，快去加购一些东西吧</p>
            </template>

            <el-table-column prop="index" label="序号"></el-table-column>
            <el-table-column prop="itemSn" label="商品编号"></el-table-column>
            <el-table-column prop="productName" label="商品名称"></el-table-column>
            <el-table-column prop="price" label="价格"></el-table-column>
            <el-table-column prop="quantity" label="数量" min-width="150px">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.quantity" :disabled="step!==2"
                                 @change="handleChangeQuantity(scope.row)" :min="1" :max="10"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column prop="operation" label="操作">
              <template slot-scope="scope">
                <el-button :disabled="step!==2" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {changeQuantity, deleteLineItem, endSale, enterItem, makeNewSale, makePayment} from '@/api/sale';
// import {validator} from '@/utils/validate.js'
export default {
  name: "SaleOrder",
  data() {
    return {
      // from规则
      rules: {
        // 有效商品编号
        itemSn: [
          {required: true, message: '商品编号不能为空'},
          {type: 'string', message: '请输入有效商品编号', trigger: 'blur'}
        ],
        quantity: [
          {required:'true', message: '商品数量为1-9', trigger: 'blur'}
        ]
      },
      saleItemList: [],
      num: 1,
      size: '',
      // 付款的form绑定内容
      makePaymentForm: {
        cashTendered: '',  // 付款金额
      },
      changeDue: '',   // 零钱
      // 录入商品的form绑定内容
      enterItemForm: {
        itemSn: '',
        quantity: ''
      },
      // 订单信息的
      orderInfo: {
        // saleNo:'',
        // total:'',
        // status:'',
        // quantity:''
      },
      // 控制按钮是否disabled
      step: 1,
      // 防抖
      timer: null,
    }
  },
  methods: {
    // 1. 开始一次新的销售
    makeNewSale() {
      this.clear();
      this.step = 2;
      // makeNewSale返回的值赋值给orderInfo
      makeNewSale().then(response => {
        this.orderInfo = response.data;
        this.$message.success(response.msg);
      })
    },
    // 2. 录入商品
    enterItem() {
      // 新增相同数据 在后端已经处理；
      // findIndex:返回符合条件的第一个元素的索引
      let index = this.saleItemList.findIndex((item) => item.itemSn === this.enterItemForm.itemSn);
      // 如果没有重复就添加
      if (index === -1) {
        // saleItemList是table绑定的内容；将enterItemForm传递给接口
        // 再将返回内容push到saleItemList中
        enterItem(this.enterItemForm).then(response => {
          // 判断是否商品编码无效
          if (response.code === 200) {
            // 返回新增的对象SaleItem订单明细在table上显示
            this.saleItemList.push(response.data);
            this.$message.success(response.msg); // 已达上限
          } else {
            this.$message.warning(response.msg);
          }
        })
      } else {
        // quantity加减;将要输入的quantity加赋到
        // this.saleItemList[index].quantity += Number(this.enterItemForm.quantity);
        this.saleItemList[index].quantity += this.enterItemForm.quantity;
      }


      // 实时更改info中的quantity变化
      // if(this.saleItemList.length === 1){
      //   this.orderInfo.quantity = list.quantity;
      // }else{
      //   this.orderInfo.quantity += list.quantity;
      // }
    },
    // 3. 停止录入商品
    endSale() {
      this.step = 4;
      endSale().then(response => {
        this.orderInfo.total = response.data;
      })
    },
    // 4. 付款
    makePayment() {
      makePayment(this.makePaymentForm).then(response => {
        if (response.code === 200) {
          this.step = 1;
          this.changeDue = response.data;
          this.$message.success(response.msg);
        } else {
          this.$message.error(response.msg);
        }
      })
    },
    // 删除订单明细
    handleDelete(row) {
      this.$confirm("是否确认删除" + row.itemSn + "该订单明细", "警告", {
        confirmButtonText: "我准备好了",
        cancelButtonText: "我再想想",
        type: "warning"
      }).then(() => {
        deleteLineItem(row.itemSn).then(response => {
          this.saleItemList.splice(row.index - 1, 1);
          this.$message.success(response.msg)
        })
      })
    },
    // 对计数器控制
    handleChangeQuantity(row) {
      // 希望在 input-number失去焦点时获取当前数据；而不是更改一次就执行 『防抖』
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        changeQuantity(row).then(response => {
          this.$message.success(response.msg)
        })
      }, 500)
    },
    // 清空页面数据
    clear() {
      this.orderInfo = {};
      this.saleItemList = [];
      this.enterItemForm = {
        itemSn: '',              // 按照form中绑定内容，录入数据的itemSn应当是 产品编号
        quantity: 1
      };
      this.makePaymentForm = {
        cashTendered: 0
      };
      this.changeDue = 0;
      this.step = 1;
    },
    // 添加table序号
    rowSaleItemIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    }
  },
}
</script>

<style scoped>
/*card*/
.el-card {
  margin-top: 10px;
}

.el-description {
  margin: 10px 0 30px 0;
}

.order_text {
  line-height: 20px;
  font-style: italic;
}
</style>